package org.orbis.memoryblock.content;

import java.nio.ByteBuffer;
import org.orbis.memorymanager.filter.DeleteFilter;

public class OptimizerContentBlock extends ContentBlock{
	public OptimizerContentBlock(ByteBuffer existingBody){
		super(existingBody);
	}

	public int checkByFilter(DeleteFilter filter, int ptr){
		long currentID = getLong(ptr, LONG);
		if(currentID <= 0) return -2; 
		if(!filter.filterID(currentID)){
			if(option[OPT_TYPE] == 0) ptr += option[OPT_APP] * PTR;
			int strlen = getInt(ptr, STRLEN);
			if(strlen < 0) return -1;
			String targetStr = getString(ptr + STRLEN, strlen);
			if(!filter.filterContent(targetStr)){
				int length = LONG + STRLEN + strlen;
				if(option[OPT_TYPE] == 0) length += option[OPT_APP] * PTR;
				return length;
			}
		}

		return -1;
	}

	public int getAvailSize(int maxLen){
		int val = 0;
		int next = 0;

		while(val < maxLen){
			next = getNextOne(val);
			if(next >= maxLen) break;
			val = next;
		}

		return val;
	}

	public void setRawBody(int from, byte[] val){
		store(val, from);
	}

	public byte[] getRawBody(int from, int to){
		return read(from, to - from);
	}

	public void moveBody(int from, int to, int offset){
		if(from >= to) throw new IllegalArgumentException("From: " + from + " >= To: " + to);
		if(from < offset) throw new IllegalArgumentException("From: " + from + " < Offset: " + offset);
		if(to + offset >= bodySize)
			throw new IllegalArgumentException("To: " + from + " >= Offset: " + offset);

		move(from, to, offset);
	}
}
